package com.hainiu.cat.web.config;

import cn.hutool.json.JSONUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * create by biji.zhao on 2021/6/4
 */
@Configuration
public class RabbitConfig {

    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("===========setConfirmCallback start=============");
            System.out.println(JSONUtil.toJsonStr(correlationData));
            System.out.println(ack);
            System.out.println(cause);
            System.out.println("===========setConfirmCallback end=============");
        });
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("===========setReturnCallback start=============");
            System.out.println(String.format("ReturnCallback消息：%s",message));
            System.out.println(String.format("ReturnCallback回应码：%s",replyCode));
            System.out.println(String.format("ReturnCallback回应信息：%s",replyText));
            System.out.println(String.format("ReturnCallback交换机：%s",exchange));
            System.out.println(String.format("ReturnCallback路由键：%s",routingKey));
            System.out.println("===========setReturnCallback end =============");
        });
        return rabbitTemplate;
    }
}
